package asrModel

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

type TranslationRequest struct {
	From            string `json:"from"`
	To              string `json:"to"`
	AudioVoiceIndex int    `json:"audioVoice"`
}

type resultWx struct {
	MessageType string `json:"message_type"`
}

// 升级为webSocket
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许所有来源
	},
}

func RealtimeTranslateHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("收到实时翻译请求")
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("WebSocket升级失败:", err)
		return
	}
	defer func(conn *websocket.Conn) {
		err := conn.Close()
		if err != nil {

		}
	}(conn)

	_, message, err := conn.ReadMessage()
	if err != nil {
		log.Println("读取消息失败:", err)
	}

	// 解析JSON数据
	var request TranslationRequest
	if err := json.Unmarshal(message, &request); err != nil {
		log.Println("解析JSON失败:", err)
	}

	sourceLanguage := request.From
	targetLanguage := request.To
	// isPlayAudioIndex 	:= request.AudioVoiceIndex
	voiceIndex := request.AudioVoiceIndex
	//fmt.Println(sourceLanguage)
	//fmt.Println(targetLanguage)

	resWx := resultWx{
		MessageType: "OK",
	}

	resWxJSON, err := json.Marshal(resWx)
	if err != nil {
		log.Printf("JSON序列化失败: %v", err)
		return
	}
	err = conn.WriteMessage(websocket.TextMessage, resWxJSON)
	if err != nil {
		log.Println()
		return
	}
	StartGummy(conn, sourceLanguage, targetLanguage, voiceIndex)
}
